package io.bdmc.modules.bss.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.bdmc.common.utils.Constant;
import io.bdmc.common.utils.MyMap;
import io.bdmc.common.utils.MyPage;
import io.bdmc.common.utils.R;
import io.bdmc.modules.bss.entity.BarHistory;
import io.bdmc.modules.bss.model.HisParam;
import io.bdmc.modules.bss.service.BarHistoryService;;

/**
 * <p>
 * 历史数据表 前端控制器
 * </p>
 *
 * @author HuangLu
 * @since 2019-01-09
 */
@RestController
@RequestMapping("/bss/his")
public class BarHistoryController {

    @Autowired
    private BarHistoryService hisSvs;

    @RequestMapping("/list")
    // @RequiresPermissions("sys:dev:list")
    public R list(HisParam param) {
        // 查询列表数据
        MyPage<BarHistory> myPage = new MyPage<BarHistory>(param.getCurrent(), param.getSize());
        MyPage<BarHistory> map = hisSvs.mySelectPage(myPage, param);
        return R.ok().putData(MyMap.ok(map.getRecords(), map.getTotal()));
    }

    @RequestMapping("/alarm")
    // @RequiresPermissions("sys:dev:list")
    public R alarm(HisParam param) {
        // 查询列表数据
        param.setDataType(3L);
        MyPage<BarHistory> myPage = new MyPage<BarHistory>(param.getCurrent(), param.getSize());
        MyPage<BarHistory> map = hisSvs.mySelectPage(myPage, param);
        return R.ok().putData(MyMap.ok(map.getRecords(), map.getTotal()));
    }



    @RequestMapping("/export")
    // @RequiresPermissions("sys:dev:list")
    public R export(HisParam param) {
        MyPage<BarHistory> myPage = new MyPage<BarHistory>(1, 5000);
        MyPage<BarHistory> map = hisSvs.mySelectPage(myPage, param);
        List<BarHistory> data = map.getRecords();
        if (data.size() == 0) {
            return R.error(-1, "查询数据为空，请更改查询条件！");
        }
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("历史数据");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String dateString = LocalDateTime.now().format(formatter);
        String fileName = "历史数据" + dateString + ".xls";// 设置要导出的文件的名字
        // 新增数据行，并且设置单元格数据
        int rowNum = 1;
        String[] headers = { "SIM卡号", "imei", "位号编码", "数据时间", "经度", "纬度", "定位精度", "偏移量（米）", "高度","电池电量","信号强度" };
        // headers表示excel表中第一行的表头
        HSSFRow row = sheet.createRow(0);
        // 在excel表中添加表头
        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
            // cell.setCellStyle(style);
        }

        // 在表中存放查询到的数据放入对应的列
        for (BarHistory d : data) {
            HSSFRow row1 = sheet.createRow(rowNum);
            row1.createCell(0).setCellValue(d.getSim() != null ? d.getSim() : "");
            row1.createCell(1).setCellValue(d.getImei() != null ? d.getImei() : "");
            row1.createCell(2).setCellValue(d.getInstallCode() != null ? d.getInstallCode() : "");
            row1.createCell(3).setCellValue(d.getDataTime().toString());
            row1.createCell(4).setCellValue(d.getLat() != null ? d.getLat() : "");
            row1.createCell(5).setCellValue(d.getLng() != null ? d.getLng() : "");
            row1.createCell(6).setCellValue(getPositioningStateString(d.getPositioningState()));
            row1.createCell(7).setCellValue(d.getShift() != null ? d.getShift() : "");
            row1.createCell(8).setCellValue(d.getHigh() != null ? d.getHigh() : "");
            row1.createCell(9).setCellValue(d.getBattery()!= null ? d.getBattery() : "");
            row1.createCell(10).setCellValue(d.getSignalStrength()!= null ? d.getSignalStrength() : "");
            rowNum++;
        }
        try {
            File path = new File("files/");
            if (!path.exists()) {
                path.mkdir();
            }
            File f = new File(path.getAbsolutePath() + "/excel/", fileName);
            if (!f.getParentFile().exists()) {
                f.getParentFile().mkdir();
            }
            FileOutputStream fileOutputStream = new FileOutputStream(f);// 指定路径与名字和格式
            workbook.write(fileOutputStream);// 将数据写出去
            fileOutputStream.close();// 关闭输出流
            return R.ok().putData("/excel/" + fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(-1, e.getMessage());
        }
    }

    private String getPositioningStateString(Integer st) {
        if(st==null){
            return "";
        }
        String re = "";
        switch (st) {
        case 1:
            re = "单点定位";
            break;
        case 2:
            re = "差分定位";
            break;
        case 3:
            re = "";
            break;
        case 4:
            re = "RTK固定解";
            break;
        case 5:
            re = "RTK浮点解";
            break;
        case 6:
            re = "推算定位";
            break;
        default:
            break;
        }
        return re;
    }
}